const { app, BrowserWindow, ipcMain, dialog, Menu, MessageChannelMain, nativeTheme, screen, contentTracing, netLog, clipboard } = require('electron')
const path = require('node:path')
const fs = require('node:fs')
const https = require('node:https')


function handleSetTitle(event, title) {
  const webContents = event.sender
  const win = BrowserWindow.fromWebContents(webContents)
  win.setTitle(title)
}

async function handleFileOpen() {
  const { canceled, filePaths } = await dialog.showOpenDialog({})
  if (!canceled) {
    return filePaths[0]
  }
}
let mainWindow
const createWindow = async () => {

  // (async () => {
  //   await contentTracing.startRecording({
  //     included_categories: ['*']
  //   })
  //   console.log('Tracing started')
  //   await new Promise(resolve => setTimeout(resolve, 5000))
  //   const path = await contentTracing.stopRecording()
  //   console.log('追踪数据记录到： ' + path)
  // })()

  // const { net } = require('electron')
  // const request = net.request('https://github.com')
  // request.on('response', (response) => {
  //   console.log(`STATUS: ${response.statusCode}`)
  //   console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
  //   response.on('data', (chunk) => {
  //     console.log(`BODY: ${chunk}`)
  //   })
  //   response.on('end', () => {
  //     console.log('No more data in response.')
  //   })
  // })
  // request.end()

  // Create a window that fills the screen's available work area.
  // const primaryDisplay = screen.getPrimaryDisplay()
  // const { width, height } = primaryDisplay.workAreaSize

  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    // minimizable: false, // 添加这一行来禁止最小化
    alwaysOnTop: true, // 添加这一行来设置窗口始终置顶
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,  // 确保这个是 true
      nodeIntegration: false   // 确保这个是 false
    }
  })

  // // 将窗口设置为始终置顶
  // mainWindow.setAlwaysOnTop(true);

  // const secondaryWindow = new BrowserWindow({
  //   show: false,
  //   webPreferences: {
  //     contextIsolation: false,
  //     preload: path.join(__dirname, 'preloadSecondary.js')
  //   }
  // })

  // // 建立通道
  // const { port1, port2 } = new MessageChannelMain()

  // // webContents准备就绪后，使用postMessage向每个webContents发送一个端口。
  // mainWindow.once('ready-to-show', () => {
  //   mainWindow.webContents.postMessage('port', null, [port1])
  // })

  // secondaryWindow.once('ready-to-show', () => {
  //   secondaryWindow.webContents.postMessage('port', null, [port2])
  // })

  const menu = Menu.buildFromTemplate([
    // {
    //   label: app.name,
    //   submenu: [
    //     {
    //       click: () => mainWindow.webContents.send('update-counter', 1),
    //       label: 'Increment'
    //     },
    //     {
    //       click: () => mainWindow.webContents.send('update-counter', -1),
    //       label: 'Decrement'
    //     }
    //   ]
    // },
    // {
    //   label: 'Electron',
    //   submenu: [{
    //     role: 'help',
    //     accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Alt+Shift+I',
    //     click: () => { console.log('Electron rocks!') }
    //   }]
    // }
  ])
  Menu.setApplicationMenu(menu)

  mainWindow.loadFile('index.html')
  // Open the DevTools.
  // mainWindow.webContents.openDevTools()


}

ipcMain.handle('dark-mode:toggle', () => {
  if (nativeTheme.shouldUseDarkColors) {
    nativeTheme.themeSource = 'light'
  } else {
    nativeTheme.themeSource = 'dark'
  }
  return nativeTheme.shouldUseDarkColors
})

ipcMain.handle('dark-mode:system', () => {
  nativeTheme.themeSource = 'system'
})


const iconName = path.join(__dirname, 'iconForDragAndDrop.png')
// const icon = fs.createWriteStream(iconName)

// Create a new file to copy - you can also copy existing files.
// fs.writeFileSync(path.join(__dirname, 'drag-and-drop-1.md'), '# First file to test drag and drop')
// fs.writeFileSync(path.join(__dirname, 'drag-and-drop-2.md'), '# Second file to test drag and drop')

// https.get('https://img.icons8.com/ios/452/drag-and-drop.png', (response) => {
//   response.pipe(icon)
// })

// 设置开机自启动
const setAutoLaunch = () => {
  app.setLoginItemSettings({
    openAtLogin: true,         // 启用开机自启动
    path: process.execPath,    // 应用程序的可执行文件路径
    // args: ['--autostart'],     // 启动时的命令行参数
    // enabled: true,             // 启用此登录项
    name: 'my-electron-app',   // 应用名称
    // openAsHidden: true,        // 启动时隐藏窗口
  })
}

app.on('ready', async () => {
  // const { systemPreferences } = require('electron')
  // console.log(systemPreferences.getEffectiveAppearance())

  // 设置开机自启动
  setAutoLaunch()

  ipcMain.handle('ping', () => 'pong')
  ipcMain.on('set-title', handleSetTitle)
  ipcMain.handle('dialog:openFile', handleFileOpen)
  ipcMain.on('counter-value', (_event, value) => {
    console.log(value) // will print value to Node console
  })

  ipcMain.handle('clipboard:writeText', (_event, text) => {
    clipboard.writeText(text)
  })

  ipcMain.handle('clipboard:readText', (_event) => {
    return clipboard.readText()
  })

  // 新增：监听来自渲染进程的窗口激活请求
  ipcMain.on('request-window-focus', () => {
    console.log('Main process: Received request-window-focus');
    if (mainWindow) {
      // 如果窗口最小化了，先恢复
      if (mainWindow.isMinimized()) {
        mainWindow.restore();
      }
      // 显示窗口（确保可见）并激活
      mainWindow.show();
      mainWindow.focus();
      console.log('Main process: Attempted to focus window.');
    } else {
      console.log('Main process: mainWindow not available.');
    }
  });

  // 在主进程中，我们接收端口对象。
  // ipcMain.on('port', (event) => {
  //   // 当我们在主进程中接收到 MessagePort 对象, 它就成为了
  //   // MessagePortMain.
  //   const port = event.ports[0]

  //   // MessagePortMain 使用了 Node.js 风格的事件 API, 而不是
  //   // web 风格的事件 API. 因此使用 .on('message', ...) 而不是 .onmessage = ...
  //   port.on('message', (event) => {
  //     // 收到的数据是： { answer: 42 }
  //     const data = event.data
  //     console.log(data)
  //   })

  //   // MessagePortMain 阻塞消息直到 .start() 方法被调用
  //   port.start()
  // })

  createWindow()

  // 获取应用版本号
  console.log(app.getVersion())

  // app.showEmojiPanel()


  // await netLog.startLogging('/path/to/net-log')
  // // After some network events
  // const path = await netLog.stopLogging()
  // console.log('Net-logs written to', path)
})

ipcMain.on('ondragstart', (event, filePath) => {
  event.sender.startDrag({
    file: path.join(__dirname, filePath),
    icon: iconName
  })
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})
